package com.zzy.demo.utils.validate.code;

import java.io.IOException;
import java.util.Objects;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import com.zzy.demo.common.constant.SysConstant;
import com.zzy.demo.common.exception.ValidateCodeException;
import com.zzy.demo.security.authentication.MyAuthenticationFailureHandler;

public class ImageCodeFilter extends OncePerRequestFilter{
	
	
	MyAuthenticationFailureHandler  myAuthenticationFailureHandler;

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		
		if("/authentication/form".equals(request.getRequestURI()) 
				&& "post".equalsIgnoreCase(request.getMethod())) {
			
			try {
				validate(request);
			}catch (ValidateCodeException exception) {
				myAuthenticationFailureHandler.onAuthenticationFailure(request, response, exception);
				return;
			}
			
		}
		
		filterChain.doFilter(request, response);
		
	}

	
	//验证逻辑
	private void validate(HttpServletRequest request) {
		
		    ImageCode codeInSession = getCodeInSession(request);
		    
	        String codeInRequest = getCodeInRequest(request);
	        
	        if (StringUtils.isBlank(codeInRequest)) {
	            throw new ValidateCodeException("验证码值不能为空");
	        }
	        if (Objects.isNull(codeInSession)) {
	            throw new ValidateCodeException("验证码不存在");
	        }
	        if (codeInSession.isExpired()) {
	            throw new ValidateCodeException("验证已过期");
	        }
	        if (!StringUtils.equals(codeInSession.getCode(), codeInRequest)) {
	            throw new ValidateCodeException("验证已不匹配");
	        }
	        
	        deleteCodeInSession(request);
	}
	
	
	
	

	private void deleteCodeInSession(HttpServletRequest request) {
		request.getSession().setAttribute(SysConstant.SESSION_KEY,null);
	}


	private String getCodeInRequest(HttpServletRequest request) {
		String code=request.getParameter("imageCode");
		return code;
	}


	private ImageCode getCodeInSession(HttpServletRequest request) {
		ImageCode  imageCode=(ImageCode) request.getSession().getAttribute(SysConstant.SESSION_KEY);
		return imageCode;
	}


	
	
	
	
	
	
	
	public MyAuthenticationFailureHandler getMyAuthenticationFailureHandler() {
		return myAuthenticationFailureHandler;
	}

	public void setMyAuthenticationFailureHandler(MyAuthenticationFailureHandler myAuthenticationFailureHandler) {
		this.myAuthenticationFailureHandler = myAuthenticationFailureHandler;
	}
	
	
	
	
	

}
